package com.itobase.statusDetect.Controller;

import com.itobase.statusDetect.Model.Classroom;
import com.itobase.statusDetect.Model.Teaching;
import com.itobase.statusDetect.Repository.ClassroomRepository;
import com.itobase.statusDetect.Repository.TeachingRepository;
import com.itobase.statusDetect.Service.ClassroomService;
import com.itobase.statusDetect.Util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;

/**
 * @author htyu
 * @date 2019/2/24
 */
@RestController
@RequestMapping("classroom")
public class ClassroomController {

    @Autowired
    ClassroomRepository classroomRepository;

    @Autowired
    ClassroomService classroomService;

    @Autowired
    TeachingRepository teachingRepository;

    @PostMapping("create")
    public Message create(@RequestBody Classroom classroom){
        try {
            return Message.success(classroomService.create(classroom));
        }catch (InvalidParameterException e){
            return Message.error("教室名重复,请勿重复添加");
        }
    }

    @GetMapping("list")
    public Message getList(@RequestParam(required = false) String keyword){
        return Message.success(classroomService.getList(keyword));
    }

    @DeleteMapping("delete")
    public Message deleteTime(@RequestBody Map<String, List<String>> map){
        List<Teaching> list;
        List<String> ids = map.get("ids");
        for(String id : ids){
            list = teachingRepository.findByClassroomID(id);
            if(list.size()==0) {
                classroomRepository.deleteById(id);
            }else{
                return Message.error("此教室在本学期或以往有过课程安排，不能删除");
            }
        }
        return Message.success("删除成功");
    }

    @GetMapping("detail")
    public Message getDetail(@RequestParam String id){
        return Message.success(classroomService.detial(id));
    }

    @PutMapping("update")
    public Message updateClassroom(@RequestBody Classroom classroom){
        try{
            return Message.success(classroomService.updateClassroom(classroom));
        }catch (InvalidParameterException e){
            return Message.error("教室名重复,请勿重复添加");
        }
    }
}
